// pages/business/myorder/myorder.js
var shihan = require('../../../common/fetch');
var config = require('../../../common/config');
var app = getApp();
var winScale = 750 / app.data.deviceInfo.windowWidth;
var range = 794 / winScale;
var pay_number = 0,
  now_brand_id = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    page: 1,
    page_size: 10,
    agentflag: true,
    agent_trade: [],
    incoming_goods: '',
    products_json: {},
    selectflag: false,
    brand_array: [],
    agent_order_list: [],
    res_navbar: ['我的进货单', '我要进货'],
    select_brand_id: '',
    determine_order_text: '',
    judgebupiao: '',
    judgebalance: '',
    bupiao: '0',
    balance: '0',
    offlineflag: true,
    is_need_load: false,
    showLoading: true,
    usebalanceflag: true,
    usebupiaoflag: true,
    order_is_pay: false,
    delete_address: 0, //是否删除了地址
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    that.setData({
      currentTab: options.index || 0
    })
    if (that.data.currentTab == 0) {
      that.setData({
        is_need_load: true
      })
      that.agentTradeList();
    } else if (that.data.currentTab == 1) {
      that.agentOrderList();
    }
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-in-out',
    });
    that.animation = animation;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    wx.getStorage({
      key: 'consignee_index',
      success: function(res) {
        if (res.data >= 0) {
          var index = res.data,
            list = that.data.agent_order_list;
          wx.getStorage({
            key: 'selectaddresskey',
            success: function(res) {
              list[index].sh_address = res.data;
              that.setData({
                agent_order_list: that.data.agent_order_list
              })
              that.getProductsJson();
              wx.removeStorage({
                key: 'consignee_index'
              });
              wx.removeStorage({
                key: 'selectaddresskey'
              });
            }
          })
          if (that.data.delete_address == 1) {
            list[index].sh_address = { sh_id: '' };
            that.setData({
              agent_order_list: that.data.agent_order_list
            })
          }
        }
      }
    })
  },
  /**
   * 页面事件
   */
  onResNavbarTap: function(e) { //collectionrem_list
    var that = this;
    that.setData({
      showLoading: true,
      currentTab: e.currentTarget.dataset.index
    });
    if (that.data.currentTab == 0) {
      that.refreshlist();
    } else if (that.data.currentTab == 1 && that.data.is_need_load) {
      that.setData({
        is_need_load: false
      })
      that.agentOrderList();
    }
  },
  agentOrderList: function() { //agent_order_select_brand  agent_order_confirm_price
    var that = this;
    shihan.sendRequest(config.agent_order_select_brand, 'POST', {
        brand_id: that.data.select_brand_id
      })
      .then(function(response) {
        if (response.data.code == 0) {
          response.data.data.sh_brand_list.forEach(function(el, index) {
            that.setData({
              brand_array: that.data.brand_array.concat(el.sh_name)
            })
          })
          response.data.data.sh_products.forEach(function(el, index) {
            el['sh_buy_qty'] = 0;
            el['sh_stock'] = 99999;
          })
          now_brand_id = response.data.data.sh_brand_id;
          that.setData({
            select_brand_id: response.data.data.sh_brand_id,
            is_top_agent: response.data.data.sh_is_top_agent, //1--A级代理商
            brand_list: response.data.data.sh_brand_list,
            determine_order_text: response.data.data.sh_is_top_agent ? '提交下单' : '确认下单',
            agent_product: response.data.data.sh_products,
            agent_address: response.data.data.sh_address,
            price_url: response.data.data.sh_price_url,
            agent_order_list: that.data.agent_order_list.concat({
              sh_address: response.data.data.sh_address,
              sh_products: response.data.data.sh_products,
              sh_product_num: 0,
              has_deltet: 0,
              is_offline: 0
            }),
          })
          that.getProductsJson();
        }
      }, function(error) {
        console.log(error);
      });
  },
  agentTradeList: function() {
    var that = this;
    shihan.sendRequest(config.agent_trade_list, 'POST', {
        page: that.data.page,
        page_size: that.data.page_size
      })
      .then(function(response) {
        if (response.data.code == 0) {
          // console.log(response);
          if (response.data.data.sh_items.length > 0) {
            that.setData({
              page: that.data.page + 1,
              agent_trade: that.data.agent_trade.concat(response.data.data.sh_items),
              showLoading: false,
              agentflag: true
            })
          } else {
            that.setData({
              showLoading: false,
              agentflag: false
            })
          }
          if (that.data.agent_trade.length == response.data.data.sh_total_rows) {
            that.setData({
              showLoading: false,
              agentflag: false
            })
          }
        } else {
          that.setData({
            showLoading: false,
            agentflag: false
          })
        }
      }, function(error) {
        console.log(error);
      });
  },
  agentOrderPrice: function() { //agent_order_select_brand  agent_order_confirm_price
    var that = this,
      data = {};
    data["brand_id"] = that.data.select_brand_id;
    data["use_bupiao"] = that.data.bupiao;
    data["use_balance"] = that.data.balance;
    data["products_json"] = JSON.stringify(that.data.products_json);
    shihan.sendRequest(config.agent_order_confirm_price, 'POST', data)
      .then(function(response) {
        if (response.data.code == 0) {
          response.data.data.sh_pay_price = Number(response.data.data.sh_pay_price);
          that.setData({
            showLoading: false,
            incoming_goods: response.data.data
          })
          that.setData({
            order_is_pay: response.data.data.sh_is_pay == 1 ? true : false
          })
          if (Number(response.data.data.sh_bupiao) == 0) {
            that.setData({
              usebupiaoflag: false
            })
          }
          if (Number(response.data.data.sh_balance) == 0) {
            that.setData({
              usebalanceflag: false
            })
          }

          // 世瀚币，现金账户显示判断
          var use_bupiao_price = 0,
            use_balance_price = 0;
          var user_bupaio = Number(response.data.data.sh_bupiao);
          var user_balance = Number(response.data.data.sh_balance);
          var pay_price = response.data.data.sh_pay_price;
          if (response.data.data.sh_use_bupiao) {
            use_bupiao_price = response.data.data.sh_use_bupiao;
          }
          if (response.data.data.sh_use_balance) {
            use_balance_price = response.data.data.sh_use_balance;
          }
          if (user_bupaio > 0) {
            that.setData({
              usebupiaoflag: true
            })
          }
          if (user_balance > 0) {
            that.setData({
              usebalanceflag: true
            })
          }
          if (that.data.bupiao == '1') {
            if (use_bupiao_price >= 0 && use_balance_price == 0 && pay_price == 0) {
              that.setData({
                balance: '0',
                judgebalance: '',
                usebalanceflag: false
              })
            }
          }
          if (that.data.balance == '1') {
            if (use_balance_price >= 0 && use_bupiao_price == 0 && pay_price == 0) {
              that.setData({
                bupiao: '0',
                judgebupiao: '',
                usebupiaoflag: false
              })
            }
          }
        }
      }, function(error) {
        console.log(error);
      });
  },
  getProductsJson: function(e) { //组合数据 products_json {"1":{"address_id":3714,"products":{"1":2,"2":1}},"2":{"address_id":3690,"products":{"1":1,"2":2}}}
    var that = this;// "is_offline":是否自提 1自提 0寄送
    that.data.agent_order_list.forEach(function(el, i) {
      that.data.products_json[i + 1] = {};
      that.data.products_json[i + 1]["products"] = {};
      that.data.products_json[i + 1]["address_id"] = el.sh_address.sh_id;
      that.data.products_json[i + 1]["is_offline"] = el.is_offline==1 ? 1 : 0;
      el.sh_products.forEach(function(ele, j) {
        that.data.products_json[i + 1]["products"][ele.sh_id] = ele.sh_buy_qty;
      })
    })
    that.setData({
      agent_order_list: that.data.agent_order_list
    })
    console.log(that.data.products_json);
    that.agentOrderPrice();
  },

  listenerPickerSelected: function(e) { //选择品牌,上一个品牌相关的编辑数据清空 products_json  incoming_goods  brand_list brand_array agent_order_list
    var that = this
    if (that.data.selectflag) {
      that.setData({
        selectflag: false
      });
    } else {
      that.setData({
        selectflag: true
      });
    }
    if (that.data.brand_list[e.detail.value].sh_id != now_brand_id) {
      that.data.brand_array.length = 0;
      that.data.agent_order_list.length = 0;
      that.setData({
        index: e.detail.value,
        brand_array: [],
        agent_order_list: [],
        products_json: {},
        incoming_goods: '',
        select_brand_id: that.data.brand_list[e.detail.value].sh_id
      });
      that.data.brand_list.length = 0;
      that.setData({
        brand_list: []
      });
      that.agentOrderList();
    }
  },
  selectArrow: function() {
    if (this.data.selectflag) {
      this.setData({
        selectflag: false
      });
    } else {
      this.setData({
        selectflag: true
      });
    }
  },
  cancelSelect: function() {
    this.setData({
      selectflag: false
    });
  },
  openAddress: function(e) { //编辑，添加地址
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    wx.setStorage({
      key: 'consignee_index',
      data: index,
      success: function() {
        wx.navigateTo({
          url: '/pages/modaddress/modaddress?id=' + id + '&floor=0',
        })
      }
    })
  },
  selectPickedup: function (e) {
    var index = e.currentTarget.dataset.index;
    var offline = e.currentTarget.dataset.offline;
    this.data.products_json[index + 1].is_offline = offline;
    this.data.agent_order_list[index].is_offline = offline;
    this.setData({
      products_json: this.data.products_json,
      agent_order_list: this.data.agent_order_list,
    })
    this.agentOrderPrice();
  },
  addGoods: function(e) { //增加产品购买数量
    this.calculateQty(e, 'add');
  },
  cutGoods: function(e) { //增加产品购买数量
    this.calculateQty(e, 'cut');
  },
  editorGoods: function(e) { //直接输入产品购买数量
    this.calculateQty(e, 'editor');
  },
  calculateQty: function(e, kind) { //计算产品购买数量 a-收货人索引; b-商品索引
    var that = this,
      product_num = 0,
      a = e.currentTarget.dataset.consignee, //收货人索引
      b = e.currentTarget.dataset.goods, //商品索引
      list = that.data.agent_order_list; //收货人列表
    if (list[a].sh_products[b].sh_buy_qty == 0 && kind == 'cut') {
      return false;
    }
    if (kind == 'editor') {
      var value = Number(e.detail.value);
      list[a].sh_products[b].sh_buy_qty = value;
      list[a].sh_product_num = value;
    } else {
      var buy_qty = Number(list[a].sh_products[b].sh_buy_qty);
      if (kind == 'add') {
        list[a].sh_products[b].sh_buy_qty = buy_qty + 1;
      } else if (kind == 'cut' && buy_qty > 0) {
        list[a].sh_products[b].sh_buy_qty = buy_qty - 1;
      }

      list[a].sh_products.forEach(function(el, index) {
        product_num = product_num + el.sh_buy_qty;
      })
      list[a].sh_product_num = product_num;
    }
    that.setData({
      agent_order_list: that.data.agent_order_list
    })
    that.getProductsJson();
  },
  addConsignee: function() { //添加收货人
    var that = this;
    that.setData({
      agent_order_list: that.data.agent_order_list.concat({
        sh_address: {
          sh_id: ''
        },
        is_offline: 0,
        sh_products: that.data.agent_product,
        sh_product_num: 0
      }),
    })
    that.data.agent_order_list.forEach(function(el, index) {
      el.has_deltet = 1;
    })
    that.setData({
      agent_order_list: that.data.agent_order_list
    })
    that.getProductsJson();
  },
  deleteConsignee: function(e) { //删除收货人
    var that = this,
      index = e.currentTarget.dataset.index;
    wx.showModal({
      content: '确定要删除改收货人吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: function(res) {
        if (res.confirm) {
          that.data.agent_order_list.splice(index, 1);
          if (that.data.agent_order_list.length == 1) {
            that.data.agent_order_list[0].has_deltet = 0;
          }
          that.setData({
            agent_order_list: that.data.agent_order_list
          })
        }
      }
    })
  },
  determineOrder: function() { //确认下单
    var that = this,
      goods_flag; //goods_flag-判断哪个收货人所有商品数量都是0，true-说明地址都已经填写，商品数量有不为0， 
    var list = that.data.agent_order_list;
    if (that.data.incoming_goods.sh_is_pay == 1) { //sh_is_pay-是否可提交 1是 0否
      for (var i = 0; i < list.length; i++) {
        goods_flag = false;
        if (!list[i].sh_address.sh_id && list[i].is_offline==0) {
          shihan.showToast.call(that, '亲，请为收货人' + (i + 1) + '添加地址哦！');
          break;
        }
        for (var j = 0; j < list[i].sh_products.length; j++) {
          if (list[i].sh_products[j].sh_buy_qty > 0) {
            goods_flag = true;
          }
        }
        if (!goods_flag) {
          shihan.showToast.call(that, '亲，请为收货人' + (i + 1) + '添加商品哦！');
          break;
        }
      }
      if (goods_flag) { //可以提交 agent_order_generate   agent_wx_perpay
        if (that.data.is_top_agent == 1) { //是A级代理商
          that.animation.translateY(-range).step();
          that.setData({
            showModalStatus: true,
            animationData: that.animation.export(),
            detailpage: false
          });
        } else { //非A级代理商
          pay_number++;
          if (pay_number == 1) {
            pay_number++;
            if (that.data.currentTab == 1) { //我要进货-付款
              var data = {};
              data["brand_id"] = that.data.select_brand_id;
              data["use_bupiao"] = that.data.bupiao;
              data["use_balance"] = that.data.balance;
              data["products_json"] = JSON.stringify(that.data.products_json);
              shihan.sendRequest(config.agent_order_generate, 'POST', data)
                .then(function(response) {
                  // console.log(response);
                  if (response.data.code == 0) {
                    shihan.showToast.call(that, '下单成功');
                    that.cleardata(1000);
                  } else {
                    shihan.showToast.call(that, response.data.msg);
                  }
                  pay_number = 0;
                }, function(error) {
                  pay_number = 0;
                });
            }
          }
        }
      }
    }
  },
  formSubmit: function(e) {
    var that = this,
      data = {},
      formId = e.detail.formId;
    pay_number++;
    that.closeModal();
    if (pay_number == 1) {
      pay_number++;
      if (that.data.currentTab == 0) { //我的进货单-付款
        wx.login({
          success: function(res) {
            shihan.sendRequest(config.agent_wx_perpay, 'POST', {
                trade_no: that.data.trade_no,
                code: res.code
              })
              .then(function(response) {
                if (response.data.code == 0) {
                  var prepayid = response.data.data.sh_package;
                  wx.requestPayment({
                    "appId": response.data.data.sh_appid,
                    'timeStamp': new String(response.data.data.sh_timestamp),
                    'nonceStr': response.data.data.sh_noncestr,
                    'package': response.data.data.sh_package,
                    'signType': 'MD5',
                    'paySign': response.data.data.sh_sign,
                    'success': function(res) {
                      that.refreshlist();
                      app.submissionForm(prepayid.split('=')[1], '3', '4');
                    },
                    'fail': function(res) {
                      app.submissionForm(formId, '1', '3');
                    }
                  })
                  pay_number = 0;
                }
              }, function(error) {
                pay_number = 0;
                console.log(error);
              });
          }
        })
      } else if (that.data.currentTab == 1) { //我要进货-付款
        data["brand_id"] = that.data.select_brand_id;
        data["use_bupiao"] = that.data.bupiao;
        data["use_balance"] = that.data.balance;
        data["products_json"] = JSON.stringify(that.data.products_json);
        shihan.sendRequest(config.agent_order_generate, 'POST', data)
          .then(function(response) {
            // console.log(response);
            if (response.data.code == 0) {
              that.setData({
                payment_status: response.data.data.sh_payment_status, //"unpaid" 红包不足以支付
                trade_no: response.data.data.sh_trade_no // 交易单号'T2017072519130313498'
              })
              if (response.data.data.sh_payment_status == 'unpaid') {
                wx.login({
                  success: function(res) {
                    shihan.sendRequest(config.agent_wx_perpay, 'POST', {
                        trade_no: that.data.trade_no,
                        code: res.code
                      })
                      .then(function(response) {
                        if (response.data.code == 0) {
                          var prepayid = response.data.data.sh_package;
                          wx.requestPayment({
                            "appId": response.data.data.sh_appid,
                            'timeStamp': new String(response.data.data.sh_timestamp),
                            'nonceStr': response.data.data.sh_noncestr,
                            'package': response.data.data.sh_package,
                            'signType': 'MD5',
                            'paySign': response.data.data.sh_sign,
                            'success': function(res) {
                              shihan.showToast.call(that, '支付成功');
                              that.cleardata(0);
                              app.submissionForm(prepayid.split('=')[1], '3', '4');
                            },
                            'fail': function(res) {
                              shihan.showToast.call(that, '支付失败');
                              that.cleardata(0);
                              app.submissionForm(formId, '1', '3');
                            }
                          })
                          pay_number = 0;
                        }
                      }, function(error) {
                        console.log(error);
                      });
                  }
                })
              } else {
                pay_number = 0;
                shihan.showToast.call(that, '支付成功');
                that.cleardata(1000);
                app.submissionForm(formId, '1', '3')
              }
            } else {
              pay_number = 0;
              shihan.showToast.call(that, response.data.msg);
            }
          }, function(error) {
            pay_number = 0;
          });
      }
    }
  },
  cleardata: function(time) { //支付成功，失败后跳转到我的进货单，并清除商品编辑信息以及收货人信息
    var that = this;
    setTimeout(function() {
      that.setData({
        currentTab: 0,
        order_is_pay: false,
        products_json: {},
        agent_order_list: [],
      });
      that.resetTrade();
      that.refreshlist();
    }, time)
  },
  resetTrade: function() {
    var that = this;
    that.data.incoming_goods.sh_qty_total = 0;
    that.data.incoming_goods.sh_subtotal = 0;
    that.data.incoming_goods.sh_products.forEach(function(el, index) {
      el['sh_price'] = 0;
      el['sh_num'] = 0;
    })
    that.data.agent_product.forEach(function(el, index) {
      el['sh_buy_qty'] = 0;
      el['sh_stock'] = 99999;
    })
    that.setData({
      incoming_goods: that.data.incoming_goods,
      agent_order_list: that.data.agent_order_list.concat({
        sh_address: that.data.agent_address,
        sh_products: that.data.agent_product,
        sh_product_num: 0,
        has_deltet: 0,
        is_offline: 0
      }),
    })
  },
  setModalStatus: function(e) {
    if (e.currentTarget.dataset.status == 0) {
      this.closeModal();
    }
  },
  closeModal: function() {
    this.animation.translateY(range).step();
    this.setData({
      showModalStatus: false,
      animationData: this.animation.export(),
      detailpage: true
    });
  },
  selectbupiao: function(e) {
    var that = this;
    if (that.data.incoming_goods.sh_bupiao > 0 && that.data.usebupiaoflag) {
      if (that.data.bupiao == '0') {
        that.setData({
          bupiao: '1',
          judgebupiao: 'select'
        })
      } else {
        that.setData({
          bupiao: '0',
          judgebupiao: ''
        })
      }
      that.agentOrderPrice();
    }
  },
  selectbalance: function(e) {
    var that = this;
    if (that.data.incoming_goods.sh_balance > 0 && that.data.usebalanceflag) {
      if (that.data.balance == '0') {
        that.setData({
          balance: '1',
          judgebalance: 'select'
        })
      } else {
        that.setData({
          balance: '0',
          judgebalance: ''
        })
      }
      that.agentOrderPrice()
    }
  },
  cancelTrade: function(e) { //我的进货单列表-取消订单
    var that = this
    var orderno = e.currentTarget.dataset.trade;
    wx.showModal({
      title: "提示",
      content: '确定要关闭该笔订单吗？',
      confirmText: "确认",
      confirmColor: "#c40000",
      showCancel: true,
      success: function(res) {
        if (res.confirm) {
          shihan.sendRequest(config.agent_trade_cancel, 'POST', {
              trade_no: orderno
            })
            .then(function(response) {
              if (response.data.code == 0) {
                shihan.showToast.call(that, '取消成功');
                that.refreshlist();
              } else {
                shihan.showToast.call(that, response.data.msg);
              }
            }, function(error) {
              console.log(error);
            });
        }
      }
    })
  },
  payTrade: function(e) { //我的进货单列表-付款
    var that = this
    shihan.sendRequest(config.agent_valid_payment, 'POST', {
        trade_no: e.currentTarget.dataset.trade
      })
      .then(function(response) {
        that.setData({
          trade_no: response.data.data.sh_trade_no,
          agent_valid_payment: response.data.data
        })
        that.animation.translateY(-range).step();
        that.setData({
          showModalStatus: true,
          animationData: that.animation.export(),
          detailpage: false
        });
      }, function(error) {
        console.log(error);
      });
  },
  orderDetail: function(e) { //订单详情
    wx.navigateTo({
      url: '/pages/business/myorderdetail/myorderdetail?index=1&tradeno=' + e.currentTarget.dataset.trade,
    })
  },
  openPriceurl: function() {
    wx.navigateTo({
      url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(this.data.price_url)
    })
  },
  refreshlist: function() {
    var that = this;
    that.data.agent_trade.length = 0;
    that.setData({
      page: 1,
      page_size: 10,
      showLoading: true,
      agent_trade: [],
    });
    that.agentTradeList();
  },
  loadMoreData: function() {
    var that = this
    if (that.data.agentflag && that.data.currentTab == 0) {
      that.setData({
        agentflag: false
      })
      this.agentTradeList();
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  }
})